﻿using BaseBll;
using BaseWebApi.App_Start;
using BaseWebApi.Common;
using BaseWebApi.Models;
using Common;
using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net.Http;
using System.Web.Http;

namespace BaseWebApi.Controllers
{
    /// <summary>
    /// 角色管理
    /// </summary>
    [ControllerGroup(groupName: "Role", useage: "系统设置-角色管理")]
    public class RoleController : BaseController
    {
        JWTPlayloadInfo playload;

        /// <summary>
        /// 查询数据列表（分页）
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetPageList(int pageSize, int pageIndex, string search = "")
        {
            string strWhere = "";
            if (!string.IsNullOrEmpty(search))
            {
                strWhere += " and RoleName like '%" + search + "%'";
            }

            DataTable dt = RoleBll.Instance.GetPageList(pageSize, pageIndex, strWhere, "SortCode", out int records);
            int totalPages = PageHelper.GetPageCount(pageSize, records);
            return JsonHelper.SuccessJson(CommonOperation.DataTable2JArray(dt), pageIndex, totalPages, records);
        }

        /// <summary>
        /// 查询数据集合
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetList(string search = "")
        {
            string strWhere = "";
            if (!string.IsNullOrEmpty(search))
            {
                strWhere += " and RoleName like '%" + search + "%'";
            }

            List<Role> list = RoleBll.Instance.GetList(strWhere);

            return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
        }

        /// <summary>
        /// 根据id获取对象实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetModelById(int id)
        {
            if (id > 0)
            {
                Role model = RoleBll.Instance.GetModelById(id);
                if (model != null)
                {
                    return JsonHelper.SuccessJson(JsonHelper.ModelToJObject(model));
                }
                else
                {
                    return JsonHelper.FailJson("数据不存在");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误");
            }
        }

        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage AddRole([FromBody] Role model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                //验证各字段合法性
                string msg = "";
                bool isOk = RoleBll.Instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    string menus = model.Menus;
                    // 获取权限
                    model.RoleValues = RoleBll.Instance.GetRoleValues(model.IsAdmain, menus);

                    //默认字段
                    model.IsDelete = 0;
                    model.RoleState = 1;
                    model.CreateTime = DateTime.Now;
                    model.CreateUser = playload.UserName;
                    bool res = RoleBll.Instance.AddRole(model);
                    if (res)
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Role, "新增角色", Constant.ActionEnum.Add, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("新增成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Role, "新增角色", Constant.ActionEnum.Add, Constant.StatusEnum.Fail));
                        return JsonHelper.FailJson("新增失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }

            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Role, "新增角色:" + ex.Message, Constant.ActionEnum.Add, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 修改角色信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateRole([FromBody] Role model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                if (model.ID <= 0)
                {
                    return JsonHelper.ErrorJson("参数错误");
                }
                bool isExist = RoleBll.Instance.IsExist(" and ID=" + model.ID);
                if (!isExist)
                {
                    return JsonHelper.ErrorJson("不存在该数据");
                }
                //验证各字段合法性
                string msg = "";
                bool isOk = RoleBll.Instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    // 获取权限
                    string menus = model.Menus;
                    model.RoleValues = RoleBll.Instance.GetRoleValues(model.IsAdmain, menus);

                    // 默认字段
                    model.UpdateTime = DateTime.Now;
                    model.UpdateUser = playload.UserName;
                    bool res = RoleBll.Instance.UpdateRole(model);
                    if (res)
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Role, "修改角色", Constant.ActionEnum.Edit, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("修改成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Role, "修改角色", Constant.ActionEnum.Edit, Constant.StatusEnum.Fail));
                        return JsonHelper.FailJson("修改失败");

                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Role, "修改角色:" + ex.Message, Constant.ActionEnum.Edit, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeleteRole(int id)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                if (id <= 0)
                {
                    return JsonHelper.FailJson("参数错误！");
                }
                else
                {
                    // 判断该角色是否被使用
                    if (RoleBll.Instance.HasUsed(id))
                    {
                        return JsonHelper.FailJson("该角色已绑定用户，不允许删除！");
                    }
                    else
                    {
                        if (RoleBll.Instance.DeleteRole(id, playload.UserName))
                        {
                            new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Role, "删除角色", Constant.ActionEnum.Delete, Constant.StatusEnum.Success));
                            return JsonHelper.SuccessJson("删除成功！");
                        }
                        else
                        {
                            new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Role, "删除角色", Constant.ActionEnum.Delete, Constant.StatusEnum.Fail));

                            return JsonHelper.FailJson("删除失败！");
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Role, "删除角色:" + ex.Message, Constant.ActionEnum.Delete, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 启用/禁用
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateStatus(int id, int status)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (id <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }

            if (status != 1 && status != 2)
            {
                return JsonHelper.ErrorJson("参数错误");
            }

            string strStatus = status == 1 ? "启用角色" : "禁用角色";

            try
            {
                // 判断是否存在该记录
                Role model = RoleBll.Instance.GetModelById(id);
                if (model == null)
                {
                    return JsonHelper.ErrorJson("数据不存在，请刷新重试");
                }

                int result = RoleBll.Instance.UpdateStatus(id, status, playload.UserName);
                if (result > 0)
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Post, strStatus, Constant.ActionEnum.Enabled, Constant.StatusEnum.Success));
                    return JsonHelper.SuccessJson(strStatus + "成功");
                }
                else
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Post, strStatus, Constant.ActionEnum.Enabled, Constant.StatusEnum.Fail));
                    return JsonHelper.FailJson(strStatus + "失败");

                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Post, strStatus + ":" + ex.Message, Constant.ActionEnum.Enabled, Constant.StatusEnum.Exception), ex);
                throw ex;
            }

        }

    }
}
